<template>
  <!-- 单独的机构组件作为打底 可往外不断填充单个组件往外扩-->
  <div id="orglist">
    <!-- <Breadcrumb :content="$store.state.curMenu.leftMenuName" v-if="!isChildren" /> -->
    <Splitpanes style="height: 100%">
      <Pane size="40" style="border: 1px solid #f5f6f7">
        <vxe-toolbar perfect ref="toolbarRef">
          <template #buttons>
            <vxe-input
              style="width: 130px"
              v-model="orgForm.searchValue"
              type="search"
              clearable
              placeholder="关键字查询"
              @clear="findOrgList"
              @keyup="keyupEnter"
              @search-click="handleSearch(orgForm.searchValue)"
            >
            </vxe-input>
            <vxe-button
              type="text"
              status="primary"
              icon="vxe-icon-refresh"
              content="刷新"
              @click="findOrgList"
            ></vxe-button>
            <vxe-button
              type="text"
              status="success"
              icon="vxe-icon-square-plus"
              content="新建"
              @click="addOrg('', '')"
            ></vxe-button>
            <vxe-button
              type="text"
              status="success"
              icon="vxe-icon-save"
              content="保存"
              @click="saveOrg"
            ></vxe-button>
            <vxe-button
              type="text"
              status="success"
              icon="vxe-icon-sort"
              content="同步数据"
              @click="pullOrg"
            ></vxe-button>
          </template>
        </vxe-toolbar>

        <div class="tableBox">
          <vxe-table
            ref="orgTable"
            border
            :data="orgaList"
            :height="conHeight + 125 + 'px'"
            :expand-config="{ expandAll: true, reserve: true }"
            @current-change="orgRowClick"
            :row-config="{ isCurrent: true, isHover: true }"
            :column-config="{ resizable: true }"
            :keyboard-config="{
              isArrow: true,
              isTab: true,
              isEdit: true
            }"
            :tree-config="{
              expandAll: true,
              transform: true,
              rowField: 'id',
              parentField: 'parentId'
            }"
            :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
            resizable
            show-overflow
            keep-source
            :reserve="true"
          >
            <vxe-column field="code" title="编码" width="120" tree-node :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="name" title="名称" min-width="110" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input type="text" :underline="false" v-model="row.name"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="操作" width="60" align="center" fixed="right">
              <template #default="{ row }">
                <el-tooltip class="item" effect="dark" content="新建子分组" placement="left">
                  <vxe-button
                    type="text"
                    status="primary"
                    icon="vxe-icon-square-plus"
                    circle
                    @click.native="addOrg(row.id, row)"
                  >
                  </vxe-button>
                </el-tooltip>
                <vxe-button
                  type="text"
                  status="danger"
                  icon="vxe-icon-delete"
                  circle
                  @click.native="deleteOrg(row.id)"
                ></vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>

      <Pane size="60"> XXX 要套用什么组件往里添加即可 </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
let { proxy }: any = getCurrentInstance();
import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
import { rowContextKey } from 'element-plus';
import { VXETable } from 'vxe-table';
import { VxeMessage } from '@/utils/CommonMessage';

// 屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

let orgForm = {
  id: '',
  parentId: null,
  parentName: '',
  name: '',
  code: '',
  tenantId: null,
  //用户输入查询内容
  searchValue: ''
};
let orgFormRule = {
  name: [
    {
      required: true,
      message: '请输入机构名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let isChildren = ref(false); //是自己单独一个页面还是集合在其他页面下 true:作为子孩子集成在其他页面下，false:自己独立一个页面
let tloading = ref(false); //加载状态
let orgTable = ref(); //机构表格

let orgaList: any = reactive([]); //机构列表数据
let currentOrg = {} as any; //当前机构

// 页面加载时更新组织机构列表(左侧)
findOrgList();

// 点击机构当前行触发的事件
function orgRowClick({ row }: any) {
  // currentOrg.value = row.value;
  // console.log('机构',row)
  proxy.$emit('getCurrentOrg', row);
  // if (IsEmpty(row)) {
  //   return;
  // }
  (proxy.$refs.orgTable as any).setCurrentRow(row);
}

// 获取机构列表(默认获得全部)
function findOrgList() {
  tloading.value = true;
  const $table = proxy.$refs.orgTable;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      // if(proxy.isChildren){
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      // }
      $table.setAllTreeExpand(true);
      // $table.loadData(orgaList,true);
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取机构列表失败','error')
    });
}

// 查询/刷新
function handleSearch(row: string | number) {
  tloading.value = true;
  const $table = orgTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0;
  proxy.$http
    .get(url, { params: { keywords: row, pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      // console.log(orgaList);
      // if(proxy.isChildren){
      //   orgRowClick({row: this.orgaList[0]})
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      $table.setAllRowExpand(true);
      $table.setAllTreeExpand(true);
      // }
      // $table.loadData(orgaList, true);
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      VxeMessage('查询刷新失败', 'error');
    });
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(orgForm.searchValue);
  }
}

// 清空搜索条件
function clearForm() {
  orgForm = {
    id: '',
    parentId: null,
    parentName: '',
    name: '',
    code: '',
    tenantId: null,
    //用户输入查询内容
    searchValue: ''
  };
}

// 同步数据
function pullOrg() {}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

// 离开时触发 进行调用接口
function handleEditClosed({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }: any) {
  // console.log('KKKKKKKKKKKKK', row, rowIndex, $rowIndex, column, columnIndex, $columnIndex);
  // // id不为空就走修改，id为空就走add
  // const url = row.id != '' && row.id != null ? '/api/sys/editOrg' : '/api/sys/addOrg';
  // proxy.$http
  //   .post(url, row)
  //   .then((res: any) => {
  //     console.log(res.data);
  //   })
  //   .catch((err: any) => {
  //     notifyMessage(err, notifyType.warning, proxy);
  //   });
}

// 新建一级机构/子结构
async function addOrg(parentids: any, row: any): Promise<void> {
  //clearForm();
  const $table = orgTable.value;
  if ($table) {
    // 获取新增的数据记录
    const record = {
      code: '',
      name: '',
      parentId: parentids != '' || parentids != null ? parentids : null,
      id: ''
    };
    // orgaList.push(record);
    // $table.loadData(orgaList);
    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveOrg() {
  const $table = proxy.$refs.orgTable;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);

    // 修改机构
    updateRecords.forEach((e: any) => {
      const url = '/api/sys/editOrg';
      const tOrganization = e;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('修改机构成功', 'success');
        })
        .catch((err: any) => {
          VxeMessage('修改机构失败', 'error');
        });
    });

    // 新增机构
    InsertRecords.forEach((ele: any) => {
      const url = '/api/sys/addOrg';
      const tOrganization = ele;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('新增机构成功', 'success');
        })
        .catch((err: any) => {
          VxeMessage('新增机构失败', 'error');
        });
    });
    findOrgList();
  }
}

// 删除机构
function deleteOrg(id: any) {
  const $table = orgTable.value;
  $table.setAllTreeExpand(true);
  $table.setAllRowExpand(true);
  proxy
    .$confirm('确定删除此组织机构？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/deleteOrgOrDept/' + id;
      proxy.$http.delete(url).then((res: any) => {
        if (res.status.code != 1) {
          VxeMessage('删除机构失败', 'error');
        } else {
          VxeMessage('删除机构成功', 'success');
        }
        findOrgList();
        $table.setAllTreeExpand(true);
      });
    })
    .catch((err: any) => {
      VxeMessage(err, 'error');
    });
}
</script>

<style lang="scss" scoped>
#orglist {
  height: 95%;

  .el-divider--vertical {
    height: 20px;
  }

  .vxe-table {
    .vxe-button {
      height: auto;
      min-width: auto;
      padding: 0.35em;
      margin-left: 0;
      font-size: 13px;
    }
    [class*=' el-icon-'],
    [class^='el-icon-'],
    [class^='icon-'] {
      font-size: 1.3em;
    }
  }
}
</style>
